<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主内容区 -->
    <div class="ml-64 p-8" style="min-width: 1000px; padding: 2rem">
      <div class="mb-6 flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <el-input
            v-model="searchQuery"
            placeholder="搜索学生姓名/学号"
            class="w-64"
            :prefix-icon="Search"
            @keyup.enter="handleSearch(searchQuery)"
          />
        </div>
      </div>

      <!-- 数据统计卡片 -->
      <el-row :gutter="24" class="mb-8">
        <el-col :span="6">
          <el-card shadow="hover" class="h-full w-full">
            <template #header>
              <div class="text-lg font-medium text-gray-600">
                <span>学生总人数</span>
              </div>
            </template>
            <div class="card-content text-center">
              <div class="text-2xl font-bold text-gray-800">
                {{ allEcharts.totalStudentCount }}
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="h-full w-full">
            <template #header>
              <div class="text-lg font-medium text-gray-600">
                <span>特殊学生总人数</span>
              </div>
            </template>
            <div class="card-content text-center">
              <div class="text-2xl font-bold text-gray-800">
                {{ allEcharts.abnormalStudentCount }}
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="h-full w-full">
            <template #header>
              <div class="text-lg font-medium text-gray-600">
                <span>每月特殊学生新增人数</span>
              </div>
            </template>
            <div class="card-content text-center">
              <div class="text-2xl font-bold text-gray-800">
                {{ allEcharts.monthlyNewStudentCount }}
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="h-full w-full">
            <template #header>
              <div class="text-lg font-medium text-gray-600">
                <span>访谈记录总次数</span>
              </div>
            </template>
            <div class="card-content text-center">
              <div class="text-2xl font-bold text-gray-800">
                {{ allEcharts.interviewRecordCount }}
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="24" class="mb-8">
        <!-- 饼状图 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="text-lg font-medium">特殊学生类型分布</div>
            </template>
            <div ref="pieChartRef" class="h-64 w-full"></div>
          </el-card>
        </el-col>

        <!-- 折线图 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="text-lg font-medium">特殊学生数量趋势</div>
            </template>
            <div ref="lineChartRef" class="h-64 w-full"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-button
        type="primary"
        size="small"
        class="custom-button"
        @click="handleImport"
      >
        <el-icon class="mr-1"> <Upload /> </el-icon>导入
        <input
          type="file"
          style="display: none"
          ref="fileInput"
          @change="handleFileChange"
        />
      </el-button>

      <el-card shadow="hover">
        <el-table :data="allStudents" style="width: 100%">
          <el-table-column prop="userName" label="学生姓名"></el-table-column>
          <el-table-column prop="account" label="学号"></el-table-column>
          <el-table-column prop="type" label="特殊类型"></el-table-column>
          <el-table-column label="轻重程度">
            <template #default="scope">
              <span
                v-if="scope.row.severity == 0"
                class="bg-green-600 text-white font-medium rounded px-2 py-1"
                >正常</span
              >
              <span
                v-else-if="scope.row.severity == 1"
                class="bg-yellow-600 text-white font-medium rounded px-2 py-1"
                >轻度</span
              >
              <span
                v-else-if="scope.row.severity == 2"
                class="bg-orange-600 text-white font-medium rounded px-2 py-1"
                >中度</span
              >
              <span
                v-else-if="scope.row.severity == 3"
                class="bg-red-600 text-white font-medium rounded px-2 py-1"
                >重度</span
              >
            </template>
          </el-table-column>
          <el-table-column label="访谈记录">
            <template #default="scope">
              共进行了{{ scope.row.count }}次访谈
            </template>
          </el-table-column>
          <el-table-column label="查看">
            <template #default="scope">
              <el-button
                type="info"
                size="small"
                icon="View"
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex items-center justify-between px-6 py-4">
          <div class="text-sm text-gray-600">共 {{ total }} 条记录</div>
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="10"
            :total="total"
            layout="prev, pager, next"
          />
        </div>
      </el-card>
    </div>

    <!-- 查看弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="学生详情"
      width="50%"
      :before-close="handleClose"
    >
      <!-- 模块切换按钮 -->
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="学生基本情况" name="basic"></el-tab-pane>
        <el-tab-pane label="学生成绩" name="score"></el-tab-pane>
        <el-tab-pane label="访谈记录" name="interview"></el-tab-pane>
      </el-tabs>

      <!-- 模块内容 -->
      <div v-if="activeTab === 'basic'" class="tab-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="学生姓名" label-width="20%">{{
            currentStudent.userName
          }}</el-descriptions-item>
          <el-descriptions-item label="学号" label-width="20%">{{
            currentStudent.account
          }}</el-descriptions-item>
          <el-descriptions-item label="特殊类型" label-width="20%">{{
            currentStudent.type
          }}</el-descriptions-item>
          <el-descriptions-item label="轻重程度" label-width="20%">
            <span
              v-if="currentStudent.severity == 0"
              class="bg-green-600 text-white font-medium rounded px-2 py-1"
            >
              正常
            </span>
            <span
              v-else-if="currentStudent.severity == 1"
              class="bg-yellow-600 text-white font-medium rounded px-2 py-1"
            >
              轻度
            </span>
            <span
              v-else-if="currentStudent.severity == 2"
              class="bg-orange-600 text-white font-medium rounded px-2 py-1"
            >
              中度
            </span>
            <span
              v-else-if="currentStudent.severity == 3"
              class="bg-red-600 text-white font-medium rounded px-2 py-1"
            >
              重度
            </span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="flex justify-end mt-4">
          <el-button type="primary" @click="editStudent">编辑</el-button>
        </div>
      </div>

      <div v-if="activeTab === 'score'" class="tab-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="绩点" label-width="20%">{{
            currentGrade.avgGpa
          }}</el-descriptions-item>
          <el-descriptions-item label="平均成绩" label-width="20%">{{
            currentGrade.avgScore
          }}</el-descriptions-item>
          <el-descriptions-item label="学科数量" label-width="20%">{{
            currentGrade.subjectCount
          }}</el-descriptions-item>
          <el-descriptions-item label="挂科数" label-width="20%">{{
            currentGrade.failureCount
          }}</el-descriptions-item>
          <el-descriptions-item label="非专业课程数量" label-width="20%">{{
            currentGrade.nonProfessionalCount
          }}</el-descriptions-item>
          <el-descriptions-item label="非专业课程平均分数" label-wdth="20%">{{
            currentGrade.nonProfesionalCouresScoreAvg
          }}</el-descriptions-item>
          <el-descriptions-item label="专业课程数量" label-width="20%">{{
            currentGrade.professionalCount
          }}</el-descriptions-item>
          <el-descriptions-item label="专业课程平均分数" label-width="20%">{{
            currentGrade.profesionalCouresScoreAvg
          }}</el-descriptions-item>
          <el-descriptions-item label="第一学期平均绩点" label-width="20%">{{
            currentGrade.firstYearOneScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第二学期平均绩点" label-width="20%">{{
            currentGrade.firstYearTwoScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第三学期平均绩点" label-width="20%">{{
            currentGrade.secondYearOneScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第四学期平均绩点" label-width="20%">{{
            currentGrade.secondYearTwoScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第五学期平均绩点" label-width="20%">{{
            currentGrade.thirdYearOneScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第六学期平均绩点" label-width="20%">{{
            currentGrade.thirdYearTwoScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第七学期平均绩点" label-width="20%">{{
            currentGrade.fourthYearOneScore
          }}</el-descriptions-item>
          <el-descriptions-item label="第八学期平均绩点" label-width="20%">{{
            currentGrade.fourthYearTwoScore
          }}</el-descriptions-item>
        </el-descriptions>
        <div class="flex justify-end mt-4">
          <el-button type="primary" @click="editGrade(currentGrade)"
            >编辑</el-button
          >
        </div>
      </div>

      <div v-if="activeTab === 'interview'" class="tab-content">
        <el-form label-position="left" label-width="20%" class="interview-form">
          <el-form-item
            v-for="(record, index) in currentRecord"
            :key="index"
            :label="`第${record.interviewCount}次访谈`"
            class="bold-label"
          >
            <el-descriptions :column="1" border>
              <el-descriptions-item label="访谈内容">{{
                record.interviewContent
              }}</el-descriptions-item>
              <el-descriptions-item label="访谈时间">{{
                record.createTime
              }}</el-descriptions-item>
              <el-descriptions-item label="教师访谈反馈记录">{{
                record.feedback
              }}</el-descriptions-item>
            </el-descriptions>
            <!-- 添加空白间隙 -->
            <div
              v-if="index !== currentRecord.length - 1"
              class="interview-gap"
            ></div>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="small"
          class="custom-button"
          @click="handleImport"
        >
          <el-icon class="mr-1"> <Upload /> </el-icon>导入
          <input
            type="file"
            style="display: none"
            ref="fileInput"
            @change="handleFile"
          />
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑学生信息弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑学生信息"
      width="50%"
      :before-close="handleEditClose"
    >
      <el-form label-position="left" label-width="20%" class="edit-form">
        <el-form-item label="学生姓名">
          <el-input v-model="currentStudent.userName"></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="currentStudent.account"></el-input>
        </el-form-item>
        <el-form-item label="特殊类型">
          <el-select v-model="currentStudent.type" placeholder="请选择">
            <el-option label="心理问题" value="心理问题"></el-option>
            <el-option label="学习困难" value="学习困难"></el-option>
            <el-option label="家庭困难" value="家庭困难"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="轻重程度">
          <el-radio-group v-model="currentStudent.severity">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">轻度</el-radio>
            <el-radio :label="2">中度</el-radio>
            <el-radio :label="3">重度</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditClose">取消</el-button>
          <el-button type="primary" @click="saveEdit(currentStudent)"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 编辑学生成绩的弹窗 -->
    <EditGradeDialog
      v-model="editGradeDialogVisible"
      :current-grade="currentGrade"
      @save-grade="saveGrade"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { Search, Plus, Upload, View } from "@element-plus/icons-vue";
import {
  getAllStudents, getAllGrade, getAllRecord, updateStudent, updateGrade, uploadStudent,
  uploadRecord, getAllEchart1, getAllEchart2, getAllEchart3,
} from "@/api/teacher/specialStudentManagement";
import EditGradeDialog from "./EditGradeDialog.vue";

const currentPage = ref(1);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(100);
const searchQuery = ref("");

// 弹窗相关状态
const dialogVisible = ref(false); // 控制弹窗显示
const activeTab = ref("basic"); // 当前选中的模块
const currentStudent = ref({}); // 当前选中的学生数据
const currentAccount = ref({});
const editDialogVisible = ref(false); // 控制编辑弹窗显示
const editGradeDialogVisible = ref(false); // 控制编辑学生成绩弹窗显示
// const currentGrade = ref([]); // 当前选中的学生成绩数据
// const currentGrade = ref({});

const statistics = [
  { label: "特殊学生总数", value: "156", trend: 5 },
  { label: "本月新增", value: "23", trend: -2 },
  { label: "待处理访谈", value: "12", trend: 8 },
  { label: "本周关注度", value: "89%", trend: 3 },
];

//获取卡片数据
const allEcharts = ref({});
//获取Echats1
function getEchart1() {
  getAllEchart1().then((response) => {
    console.log("Echart1数据返回", response);
    allEcharts.value = response;
  });
}

const pieChartRef = ref(null);
let pieChartInstance = null;
const allEchart2 = ref({});
// 初始化饼状图
// 获取饼状图数据
function getEchart2() {
  getAllEchart2()
    .then((response) => {
      console.log("Echart2数据返回", response);
      allEchart2.value = response;
      console.log("allEchart2数据返回", allEchart2.value);

      // 确保 DOM 和数据都已加载
      if (pieChartRef.value && allEchart2.value) {
        initPieChart();
      } else {
        console.error("饼状图数据或 DOM 未正确加载");
      }
    })
    .catch((error) => {
      console.error("获取饼状图数据失败", error);
    });
}

// 初始化饼状图
function initPieChart() {
  if (!pieChartInstance) {
    pieChartInstance = echarts.init(pieChartRef.value);
  }

  // 将后端返回的数据转换为 ECharts 需要的格式
  const data = allEchart2.value.map((item) => ({
    name: item.type,
    value: item.count,
  }));

  // 设置饼状图配置
  pieChartInstance.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "类别分布",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
        },
        data,
      },
    ],
  });

  // 监听窗口变化，自动调整图表大小
  window.addEventListener("resize", () => {
    pieChartInstance.resize();
  });
}
// 在组件卸载前销毁 ECharts 实例
onBeforeUnmount(() => {
  if (pieChartInstance) {
    pieChartInstance.dispose();
    pieChartInstance = null;
  }
});

// 折线图 DOM 引用
const lineChartRef = ref(null);
let lineChartInstance = null;

// 折线图数据
const allEchart3 = ref({});

// 获取折线图数据
function getEchart3() {
  getAllEchart3()
    .then((response) => {
      console.log("Echart3数据返回", response);
      allEchart3.value = response; // 更新 allEchart3 的值
      initLineChart(); // 初始化折线图
    })
    .catch((error) => {
      console.error("获取折线图数据失败", error);
    });
}

// 初始化折线图
function initLineChart() {
  if (!lineChartInstance) {
    lineChartInstance = echarts.init(lineChartRef.value);
  }

  // 将后端返回的数据转换为 ECharts 需要的格式
  const xAxisData = allEchart3.value.map((item) => {
    const date = new Date(item.localDate);
    return `${date.getMonth() + 1}月`; // 提取月份并格式化为 "X月"
  });

  const yAxisData = allEchart3.value.map((item) => item.counts); // 提取 counts

  // 设置折线图配置
  lineChartInstance.setOption({
    tooltip: {
      trigger: "axis",
      formatter: "月份: {b}<br/>数量: {c}",
    },
    xAxis: {
      type: "category",
      data: xAxisData, // X 轴数据
      axisLabel: {
        formatter: function (value) {
          return value; // 直接显示月份
        },
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "特殊学生数量",
        type: "line",
        data: yAxisData, // Y 轴数据
        smooth: true, // 平滑曲线
        itemStyle: {
          color: "#409EFF", // 折线颜色
        },
      },
    ],
  });

  // 监听窗口变化，自动调整图表大小
  window.addEventListener("resize", () => {
    lineChartInstance.resize();
  });
}

// 在组件卸载前销毁 ECharts 实例
onBeforeUnmount(() => {
  if (lineChartInstance) {
    lineChartInstance.dispose();
    lineChartInstance = null;
  }
});

onMounted(() => {
  getEchart2();
  getEchart3();
});

const allStudents = ref([]);

// 获取学生列表
function getStudents(data) {
  getAllStudents(data).then((response) => {
    console.log("列表数据返回", response);
    allStudents.value = response.rows;
    total.value = response.total;
  });
}

// 加载学生列表
onMounted(() => {
  let params = {
    key: searchQuery.value,
    page: pageNum.value,
    size: pageSize.value,
  };
  getStudents(params);
  getEchart1();
});

// 模糊搜索
const handleSearch = (data) => {
  searchQuery.value = data;
  let params = {
    key: searchQuery.value,
    page: pageNum.value,
    size: pageSize.value,
  };
  getStudents(params);
};

//查看弹窗
const handleView = (row) => {
  currentStudent.value = row;
  console.log("成绩账号", row.account);
  currentAccount.value = row.account;
  let params = {
    account: currentAccount.value,
  };
  dialogVisible.value = true;
  getGrade(params);
  getRecord(params);
};

// 处理关闭弹窗事件
const handleClose = () => {
  currentGrade.value = [];
  currentRecord.value = [];
  dialogVisible.value = false;
};

//获取成绩
let currentGrade = ref([]);
function getGrade(data) {
  getAllGrade(data).then((response) => {
    console.log("成绩数据返回", response);
    currentGrade.value = response;
    console.log("个人成绩", currentGrade);
  });
}

//获取访谈记录
let currentRecord = ref([]);
function getRecord(data) {
  getAllRecord(data).then((response) => {
    console.log("访谈记录返回", response);
    currentRecord.value = response;
    console.log("个人访谈", currentGrade);
  });
}

//编辑学生信息的弹窗
const editStudent = () => {
  editDialogVisible.value = true;
};

// 保存学生信息编辑信息
const saveEdit = (data) => {
  let info = {
    account: data.account,
    userName: data.userName,
    type: data.type,
  };
  updateStudent(info).then(function (response) {
    let params = {
      key: searchQuery.value,
      page: pageNum.value,
      size: pageSize.value,
    };
    getStudents(params);
    getEchart2();
  });
  // ElMessage.success("编辑成功");
  editDialogVisible.value = false;
};

// 关闭学生信息编辑弹窗
const handleEditClose = () => {
  editDialogVisible.value = false;
};

//打开成绩弹窗
//编辑学生信息的弹窗
const editGrade = (grade) => {
  currentGrade.value = { ...grade }; // 确保 currentGrade 是一个对象
  editGradeDialogVisible.value = true;
  console.log(editDialogVisible.value);
};

// 保存学生成绩
const saveGrade = (grade) => {
  let params = {
    avgGpa: grade.avgGpa,
    avgScore: grade.avgScore,
    failurecount: grade.failureCount,
    firstYearOneScore: grade.firstYearOneScore,
    firstYearTwoScore: grade.firstYearTwoScore,
    fourthYearOneScore: grade.fourthYearOneScore,
    fourthYearTwoScore: grade.fourthYearTwoScore,
    nonProfesionalcouresScoreAvg: grade.nonProfesionalCouresScoreAvg,
    nonProfessionalcount: grade.nonProfessionalCount,
    profesionalcouresScoreAvg: grade.profesionalCouresScoreAvg,
    professionalcount: grade.professionalcount,
    secondYearOneScore: grade.secondYearOneScore,
    secondYearTwoScore: grade.secondYearTwoScore,
    subjectcount: grade.subjectcount,
    thirdYearOneScore: grade.thirdYearOneScore,
    thirdYearTwoScore: grade.thirdYearTwoScore,
    studentAccount: grade.studentAccount,
    id: grade.id,
  };
  updateGrade(params).then((response) => {
    ElMessage.success("编辑成功");
    getGrade({ account: grade.studentAccount });
    editGradeDialogVisible.value = false;
  });
};

const fileInput = ref();
// 导入功能
const handleImport = () => {
  fileInput.value.click();
};
//导入学生
function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData();
    formData.append("file", file);
    uploadStudent(formData).then((response) => {
      ElMessage.success("导入成功");
      getStudents({
        key: searchQuery.value,
        page: pageNum.value,
        size: pageSize.value,
      });
    });
  } else {
    ElMessage.error("未选择文件");
  }
}
//导入访谈
function handleFile(event) {
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("account", currentAccount.value);
    uploadRecord(formData).then((response) => {
      ElMessage.success("导入成功");
      getRecord({ account: currentAccount.value });
    });
  } else {
    ElMessage.error("未选择文件");
  }
}

//折线图

// onMounted(() => {
//   if (lineChartRef.value) {
//     const lineChart = echarts.init(lineChartRef.value);
//     lineChart.setOption({
//       animation: false,
//       tooltip: {
//         trigger: "axis",
//       },
//       xAxis: {
//         type: "category",
//         data: ["1月", "2月", "3月", "4月", "5月", "6月"],
//       },
//       yAxis: {
//         type: "value",
//       },
//       series: [
//         {
//           data: [120, 132, 101, 134, 90, 230],
//           type: "line",
//           smooth: true,
//         },
//       ],
//     });
//   }
// });
</script>

<style scoped>
.bg-green-600 {
  background-color: rgba(8, 147, 80, 0.5);
}
.bg-yellow-600 {
  background-color: rgba(249, 191, 75, 0.5);
}
.bg-orange-600 {
  background-color: rgba(249, 129, 75, 0.5);
}
.bg-red-600 {
  background-color: rgba(249, 75, 75, 0.5);
}

.el-menu {
  border-right: none;
}

.el-card {
  margin-bottom: 20px;
}

.special-student__chart {
  height: 300px;
}

.button-group {
  display: inline-flex;
  gap: 8px; /* 根据需要调整间距 */
}

.custom-button {
  margin-bottom: 16px; /* 添加下边距 */
}

.tab-content {
  margin-top: 20px;
}

.interview-form .el-form-item {
  margin-bottom: 20px; /* 添加表单项之间的间距 */
}

.interview-form .interview-gap {
  height: 20px; /* 添加访谈记录之间的空白间隙 */
}

.interview-form .bold-label {
  font-weight: bold;
}

.el-card {
  width: 100%;
  height: auto;
}

.el-card__body {
  padding: 10px;
}

.card-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* Ensure the content area takes up full height */
}
</style>
